<template>
    <div style="margin-left: 25px; margin-top: 15px">
        <!--查询条件-->
        <el-form :inline="true" :model="search" class="demo-form-inline">
            <el-form-item label="断奶日期">
                <el-date-picker v-model="search.date" type="datetimerange" range-separator="-"
                    start-placeholder="Start date" end-placeholder="End date" value-format="YYYY-MM-DD"
                    style="width: 240px" />
            </el-form-item>
            <el-form-item label="种母耳号">
                <el-input v-model="search.Earbugles" clearable />
            </el-form-item>
            <el-form-item label="转入栋舍">
                <el-select v-model="search.InBuildings" clearable style="width: 200px">
                    <el-option :label="item.Name" :value="item.Name" v-for="item in CottagerList" :key="item.Id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="danger" size="default" :icon="Search" @click="GetWeaningList">查询</el-button>
            </el-form-item><br />
            <el-form-item label="负责人" style="margin-left: 14px">
                <el-select v-model="search.head" clearable style="width: 200px">
                    <el-option :label="item.name" :value="item.name" v-for="item in HeadList" :key="item.id" />
                </el-select>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div style="margin-top: 9px">
            <el-button type="danger" size="default" :icon="Plus" @click="openCreate">新增</el-button>
            <el-button type="danger" size="default" :icon="Delete" @click="DelAll">删除</el-button>
        </div>

        <!-- 列表 -->
        <div style="margin-top: 25px">
            <el-table :data="WeaningList" stripe style="width: 85%" @selection-change="GetWeaningIds">
                <el-table-column type="selection" width="35" fixed align="center" />
                <el-table-column label="序号" align="center" fixed>
                    <template #default="a">
                        <span>{{
                            a.$index + (page.pageIndex - 1) * page.pageSize + 1
                            }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="weaningDate" label="断奶日期" align="center" width="130">
                    <template v-slot="a">
                        <span v-if="a.row.weaningDate">
                            {{ a.row.weaningDate.substring(0, 10) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="earbugles" label="耳号" align="center" width="130" />
                <el-table-column prop="lacationDays" label="哺乳天数" align="center" width="130" />
                <el-table-column prop="weaningweight" label="种母重量(公斤)" align="center" width="130">
                    <template v-slot="a">
                        <span v-if="a.row.weaningweight">{{ a.row.weaningweight.toFixed(2) }}公斤</span>
                    </template>
                </el-table-column>
                <el-table-column prop="weaningnumber" label="断奶只数" align="center" width="130" />
                <el-table-column prop="weaningAllweight" label="断奶总窝重(公斤)" align="center" width="150" />
                <el-table-column prop="currentbuilding" label="当前栋舍" align="center" width="130" />
                <el-table-column prop="currentfield" label="当前栏位" align="center" width="130" />
                <el-table-column prop="transferbuilding" label="转入栋舍" align="center" width="130" />
                <el-table-column prop="transferfileld" label="转入栏位" align="center" width="130" />
                <el-table-column prop="weaningreason" label="断奶原因" align="center" width="130" />
                <el-table-column prop="head" label="负责人" align="center" width="130px" />
                <el-table-column prop="createBy" label="创建人" align="center" />
                <el-table-column prop="createDate" label="创建时间" align="center" width="130px">
                    <template v-slot="a">
                        <span v-if="a.row.createDate">
                            {{ a.row.createDate.substring(0, 10) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updateBy" label="修改人" align="center" />
                <el-table-column prop="updateDate" label="修改时间" align="center" width="130px">
                    <template v-slot="a">
                        <span v-if="a.row.updateDate">
                            {{ a.row.updateDate.substring(0, 10) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="130px">
                    <template v-slot="a">
                        <el-link type="primary" style="margin-right: 15px" @click="openUpdate(a.row.swId)">编辑</el-link>
                        <el-link type="primary" @click="weaningDel(a.row.swId)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <table style="margin: auto; margin-left: 300px; margin-top: 25px">
            <tbody>
                <tr>
                    <td>
                        <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                            :page-sizes="[15, 20, 35, 50]" :background="true" layout="total, slot,sizes"
                            :total="page.totalCount" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                            <span>，共{{ page.pageCount }}页，当前第{{ page.pageIndex }}/{{
                                page.pageCount
                                }}页</span>
                        </el-pagination>
                    </td>
                    <td>
                        <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                            :page-sizes="[15, 20, 35, 50]" :background="true" layout="slot, prev, pager, next"
                            :total="page.totalCount" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                            <button class="btn-prev" @click="handleCurrentChange(1)" :disabled="page.pageIndex == 1">
                                首页
                            </button>
                        </el-pagination>
                    </td>
                    <td>
                        <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                            :page-sizes="[15, 20, 35, 50]" :background="true" layout="slot, jumper"
                            :total="page.totalCount" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                            <button class="btn-next" @click="handleCurrentChange(page.pageCount)"
                                :disabled="page.pageIndex == page.pageCount">
                                尾页
                            </button>
                        </el-pagination>
                    </td>
                </tr>
            </tbody>
        </table>

        <!-- 弹出层添加 -->
        <el-dialog v-model="dialogVisible" title="添加种母断奶信息" width="1300" style="height: 600px;">
            <span>
                <div class="dialog-footer">
                    <div style="margin-left: 25px;margin-top: 15px">
                        <div>
                            <el-button type="danger" size="default" :icon="Plus" @click="AddRow"
                                v-show="weaningInfo.swId == 0">新增</el-button>
                            <el-button type="danger" size="default" :icon="Document" @click="WeaningCreate"
                                v-show="weaningInfo.swId == 0">保存</el-button>
                            <el-button type="danger" size="default" :icon="Document" v-show="weaningInfo.swId != 0"
                                @click="weaningUpd">修改</el-button>

                        </div>
                        <div style="margin-top: 25px;margin-left: 25px">
                            <el-form :inline="true" :model="weaningInfo" class="demo-form-inline">
                                <el-form-item label="*负责人">
                                    <el-select v-model="weaningInfo.head" filterable placeholder="请选择"
                                        style="width: 110px" @change="">
                                        <el-option v-for="item in HeadList" :key="item.name" :label="item.name"
                                            :value="item.name" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="*断奶日期">
                                    <el-date-picker v-model="weaningInfo.weaningDate" type="date" placeholder="请选择"
                                        clearable value-format="YYYY-MM-DD" style="width: 150px;" />
                                </el-form-item>
                            </el-form>
                        </div>
                        <div style="margin-top: 35px;">
                            <el-table style="width: 90%" :data="RowList">
                                <el-table-column label="序号" align="center">
                                    <template #default="a">
                                        <span>{{ a.$index + (page.pageIndex - 1) * page.pageSize + 1 }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="*耳号" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-select v-model="weaningInfo.earbugles" filterable placeholder="请输入"
                                                style="width: 98px" @change="GetSheepInfo">
                                                <el-option v-for="item in ZMEarList" :key="item.name" :label="item.name"
                                                    :value="item.name" />
                                            </el-select>
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="哺乳天数" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-input v-model="weaningInfo.lacationDays" style="width: 98px" readonly />
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="当前栋舍" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-input v-model="weaningInfo.currentbuilding" style="width: 98px"
                                                readonly />
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="当前栏位" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-input v-model="weaningInfo.currentfield" style="width: 98px" readonly />
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="转入栋舍" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-select v-model="weaningInfo.transferbuilding" clearable
                                                style="width: 98px;" @change="InGetHandleGetSheepFarm">
                                                <el-option :label="item.Name" :value="item.Name"
                                                    v-for="item in InCottagerList" />
                                            </el-select>
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="转入栏位" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-select v-model="weaningInfo.transferfileld" clearable
                                                style="width: 110px;">
                                                <el-option :label="item.Name" :value="item.Name"
                                                    v-for="item in InColunmList" :key="item.Id" />
                                            </el-select>
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="*断奶只数(只)" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-input v-model="weaningInfo.weaningnumber" style="width: 98px" />
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="*断奶总窝重(公斤)" align="center" width="140">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-input v-model="weaningInfo.weaningAllweight" style="width: 98px" />
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="种母重量(公斤)" align="center" width="130">
                                    <template v-slot="a">
                                        <span v-if="activeIndex == a.$index">
                                            <el-input v-model="weaningInfo.weaningweight" style="width: 98px" />
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </span>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Document, Delete, Back, Search } from "@element-plus/icons-vue";
import Enumerable from "linq";
import http from "@/http";



//打开修改弹出层
const openUpdate = (id: any) => {
    dialogVisible.value = true;
    RowList.value = [];
    AddRow();
    http.get("RouteRead/api/Weanings/WeaningBackfill?Id=" + id).then(x => {
        var info = x.data;
        weaningInfo.swId = info.swId;
        weaningInfo.head = info.head;
        weaningInfo.weaningDate = info.weaningDate;
        weaningInfo.earbugles = info.earbugles;
        weaningInfo.lacationDays = info.lacationDays;
        weaningInfo.currentbuilding = info.currentbuilding;
        weaningInfo.currentfield = info.currentfield;
        weaningInfo.transferbuilding = info.transferbuilding;
        weaningInfo.transferfileld = info.transferfileld;
        weaningInfo.weaningnumber = info.weaningnumber;
        weaningInfo.weaningAllweight = info.weaningAllweight;
        weaningInfo.weaningweight = info.weaningweight;
        weaningInfo.createBy = info.createBy;
        weaningInfo.createDate = info.createDate;
        weaningInfo.updateBy = info.updateBy;
        weaningInfo.updateDate = info.updateDate;
        weaningInfo.isDel = info.isDel;
    })
}
//修改种母断奶信息
const weaningUpd = () => {
    //根据耳号获取种母历史记录信息
    http.get("RouteRead/api/Historys/HistoryEarsel?EarNumber=" + weaningInfo.earbugles).then(res => {
        var info = res.data;


        SheepUpd.earNumber = weaningInfo.earbugles;
        SheepUpd.cottage = weaningInfo.transferbuilding;
        SheepUpd.field = weaningInfo.transferfileld;
        http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)

        http.put("Kroute/api/Weanings/WeaningUpdate", weaningInfo).then(x => {
            if (x.data > 0) {
                ElMessage.success("种母断奶信息修改成功")
                dialogVisible.value = false;
                GetWeaningList();

                //更改档案的繁殖状态
                http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + weaningInfo.earbugles).then(res => {
                    var form = res.data;
                    form.reproductiveState = 6;
                    form.pregnancyTest = false;
                    http.put("Mroute/api/SheepFile/SheepFileConditionUpdate", form)
                })

                info.weaningDate = weaningInfo.weaningDate;//断奶日期
                info.weaningNumber = weaningInfo.weaningnumber;//断奶只数
                info.weightOfWeaningLitter = weaningInfo.weaningAllweight;//断奶窝重
                info.isEnd = true;
                //更改种母历史记录
                http.post("Kroute/api/Historys/HistoryCreate", info);
            } else {
                ElMessage.error("种母断奶信息修改失败")
            }
        })
    })


}


//批量删除
var ShiftIds = ref("");
const GetWeaningIds = (ids: any) => {
    ShiftIds.value = "";
    for (let index = 0; index < ids.length; index++) {
        ShiftIds.value += ids[index].sdId + ",";
    }
}
const AllOronly = ref(false);
const DelAll = () => {
    AllOronly.value = true;
    weaningDel(ShiftIds.value.substring(0, ShiftIds.value.length - 1));
}

//删除转舍信息
const weaningDel = (id: any) => {
    ElMessageBox.confirm(
        '确定要删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            http.delete("Kroute/api/Weanings/WeaningDelete?Ids=" + id).then(x => {
                if (x.data > 0) {
                    if (AllOronly.value == true) {
                        AllOronly.value = false;
                        var ids = id.split(",");
                        ids.forEach((a: any) => {
                            http.get("RouteRead/api/Weanings/WeaningBackfill?Id=" + a).then(x => {
                                SheepUpd.earNumber = x.data.earbugles;
                                SheepUpd.cottage = x.data.currentbuilding;
                                SheepUpd.field = x.data.currentfield;
                                http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)
                            })
                        });
                    } else {
                        http.get("RouteRead/api/Weanings/WeaningBackfill?Id=" + id).then(x => {
                            SheepUpd.earNumber = x.data.earbugles;
                            SheepUpd.cottage = x.data.currentbuilding;
                            SheepUpd.field = x.data.currentfield;
                            http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)
                        })
                    }
                    ElMessage.success("删除成功")
                    GetWeaningList();
                } else {
                    ElMessage.error("删除失败")
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消操作',
            })
        })
}


//控制弹出层显示
const dialogVisible = ref(false);
//打开添加弹出层
const openCreate = () => {
    dialogVisible.value = true;
    RowList.value = [];
}
const WeaningCreate = () => {
    //根据耳号获取种母历史记录信息
    http.get("RouteRead/api/Historys/HistoryEarsel?EarNumber=" + weaningInfo.earbugles).then(res => {
        var info = res.data;

        if (!weaningInfo.head) {
            ElMessage.error("请选择负责人");
            return;
        }
        if (!weaningInfo.weaningDate) {
            ElMessage.error("请选择断奶日期");
            return;
        }
        if (!weaningInfo.earbugles) {
            ElMessage.error("请选择耳号");
            return;
        }
        if (!weaningInfo.weaningnumber) {
            ElMessage.error("请输入断奶只数");
            return;
        }
        if (!weaningInfo.weaningAllweight) {
            ElMessage.error("请输入断奶总窝重");
            return;
        }

        //更改档案信息的栋舍信息
        SheepUpd.earNumber = weaningInfo.earbugles;
        SheepUpd.cottage = weaningInfo.transferbuilding;
        SheepUpd.field = weaningInfo.transferfileld;
        http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)

        http.post("Kroute/api/Weanings/WeaningCreate", weaningInfo).then(x => {
            if (x.data > 0) {
                ElMessage.success("种母断奶信息保存成功")
                dialogVisible.value = false;
                GetWeaningList();

                //更改档案的繁殖状态
                http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + weaningInfo.earbugles).then(res => {
                    var form = res.data;
                    form.reproductiveState = 6;
                    form.pregnancyTest = false;
                    http.put("Mroute/api/SheepFile/SheepFileConditionUpdate", form)
                })

                info.weaningDate = weaningInfo.weaningDate;//断奶日期
                info.weaningNumber = weaningInfo.weaningnumber;//断奶只数
                info.weightOfWeaningLitter = weaningInfo.weaningAllweight;//断奶窝重
                info.isEnd = true;
                //更改种母历史记录
                http.post("Kroute/api/Historys/HistoryCreate", info);
            } else {
                ElMessage.error("种母断奶信息保存失败")
            }
        })
    })
}



//新增行操作
var activeIndex = ref(-1);
var RowList = ref<{}[]>([])
const AddRow = () => {
    var newRow = {
        "swId": 0,
        "earbugles": null,
        "head": null,
        "weaningDate": null,
        "lacationDays": 0,
        "currentbuilding": null,
        "currentfield": null,
        "transferbuilding": null,
        "transferfileld": null,
        "weaningnumber": null,
        "weaningAllweight": null,
        "weaningweight": null,
        "weaningreason": null
    }
    RowList.value.push(newRow);
    activeIndex.value = RowList.value.length - 1;
}

//种母断奶表单
const weaningInfo = reactive({
    "createBy": "string",
    "createDate": "2024-05-13T00:40:55.597Z",
    "updateBy": "string",
    "updateDate": "2024-05-13T00:40:55.597Z",
    "isDel": false,
    "swId": 0,
    "earbugles": null,
    "head": null,
    "weaningDate": null,
    "lacationDays": null,
    "currentbuilding": null,
    "currentfield": null,
    "transferbuilding": null,
    "transferfileld": null,
    "weaningnumber": null,
    "weaningAllweight": null,
    "weaningweight": null,
    "weaningreason": null
})

//查询条件
const search = ref({
    date: [],
    Earbugles: "",
    InBuildings: "",
    head: "",
});
//分页数据
const page = reactive({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    pageCount: 0,
});
//种母断奶列表
const WeaningList = ref([]);
//获取种母断奶集合
const GetWeaningList = () => {
    var dates = "";
    if (search.value.date) {
        dates = search.value.date.join(",");
    }
    http.get("RouteRead/api/Weanings/WeaningSelect", {
        params: {
            pageIndex: page.pageIndex,
            pageSize: page.pageSize,
            InDate: dates,
            Earbugles: search.value.Earbugles,
            InBuildings: search.value.InBuildings,
            Head: search.value.head,
        }
    }).then(x => {
        WeaningList.value = x.data.datas;
        page.totalCount = x.data.totalCount;
        page.pageCount = x.data.pageCount;
    })
}
const handleSizeChange = (val: any) => {
    page.pageSize = val;
    GetWeaningList();
};
const handleCurrentChange = (val: any) => {
    page.pageIndex = val;
    GetWeaningList();
};

//获取负责人信息
interface selectList {
    id: "";
    name: "";
}
const HeadList = ref<selectList[]>([]);
const GetHeadList = () => {
    http.get("Readroute/api/StaffInfo/GetStaff").then((x) => {
        HeadList.value = x.data;
    });
};

//栋舍
const CottagerList = ref<
    {
        Id: "";
        Name: "";
    }[]
>([]);
const GetHandleGetCot = () => {
    http.get("OrganizationRead/api/Cottage/HandleGetCot").then((x) => {
        CottagerList.value = x.data;
    });
};
const ColunmList = ref<
    {
        CottageId: "";
        Id: "";
        Name: "";
    }[]
>([]);
const GetHandleGetSheepFarm = () => {
    if (1) {
        http.get("OrganizationRead/api/Field/HandleGetSheepFarm?Id=").then(x => {
            ColunmList.value = x.data;
        })
    }
}

//计算日期之间的天数
const DateDiffer = (Date_end: any) => {
    //date1结束时间
    let date1 = new Date(Date_end);
    //date2当前时间
    let date2 = new Date();
    // date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
    // date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
    const diff = date2.getTime() - date1.getTime(); //目标时间减去当前时间
    const diffDate = diff / (24 * 3600 * 1000); //计算当前时间与结束时间之间相差天数
    return Math.ceil(diffDate);
};

//根据耳号获取羊只档案信息
const GetSheepInfo = () => {
    http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + weaningInfo.earbugles).then(x => {
        weaningInfo.currentbuilding = x.data.cottage;
        weaningInfo.currentfield = x.data.field;

        http.get("RouteRead/api/Deliverys/DeliveryEarsel?EarNumber=" + weaningInfo.earbugles).then(res => {
            var maxDate = Enumerable.from(res.data).max((a: any) => a.deliveryDate);
            weaningInfo.lacationDays = DateDiffer(maxDate);
        })
    })
}

//转入栋舍和栏位
const InCottagerList = ref<{
    Id: "",
    Name: ""
}[]>([]);
const InGetHandleGetCot = () => {
    http.get("OrganizationRead/api/Cottage/HandleGetCot").then(x => {
        InCottagerList.value = x.data;
    })
}
const InColunmList = ref<{
    CottageId: "",
    Id: "",
    Name: ""
}[]>([]);
const InGetHandleGetSheepFarm = () => {
    if (weaningInfo.transferbuilding) {
        http.get("OrganizationRead/api/Field/HandleGetSheepFarm?Id=" + weaningInfo.transferbuilding).then(x => {
            InColunmList.value = x.data;
        })
    }
}

//获取种公种母后裔耳标（分类后）
const ZMEarList = ref<{
    name: ""
}[]>([]);
const ZGEarList = ref<{
    name: ""
}[]>([]);
const HYEarList = ref<{
    name: ""
}[]>([]);
const GetEarList = () => {
    http.get("MYroute/api/SheepFile/SheepFileConditionarchives").then(x => {
        x.data.forEach((a: any) => {
            if (a.sheepType == "种母" && a.reproductiveState == "哺乳") {
                ZMEarList.value.push({
                    name: a.card
                })
            } else if (a.sheepType == "种公") {
                ZGEarList.value.push({
                    name: a.card
                })
            } else {
                HYEarList.value.push({
                    name: a.card
                })
            }
        });
    })
}

//修改羊只档案信息
var SheepUpd = reactive({
    earNumber: null,
    cottage: null,
    field: null,
})

onMounted(() => {
    GetEarList();
    GetHeadList();
    GetHandleGetCot();
    InGetHandleGetCot();
    GetWeaningList();
})

</script>

<style></style>